import 'dart:async';
import 'dart:ui';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/share_poster_menu_dialog.dart';
import 'package:e_reception_flutter/singleton/share_repository/share_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_folder_detail_event.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_folder_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_common_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_detail_type_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/expandable_text.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart' as prefix ;
import 'package:webview_flutter/webview_flutter.dart';
import '../smart_home_upload_service.dart';

///文件夹、动态详情
class SmartHome3DLinkDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHome3DLinkDetailPage";
  final String scid;
  final String title;
  ///01图片 02视频 03链接
  final String type;
  final SmartHomeFolderDetailDataBean folderDetail;
  final List<ColumnListBean> columnList;
  final int selectIndex;

  const SmartHome3DLinkDetailPage({
    Key key,
    this.scid,
    this.type,
    this.title,
    this.folderDetail,
    this.columnList,
    this.selectIndex,
  }) : super(key: key);

  @override
  _SmartHome3DLinkDetailPageState createState() =>
      _SmartHome3DLinkDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context,
      String scid, String type, String title,
      SmartHomeFolderDetailDataBean folderDetail,
      List<ColumnListBean> columnList,{int selectIndex}) {
    return RouterUtils.routeForFutureResult(
        context,
        SmartHome3DLinkDetailPage(
          scid: scid,
          type: type,
          title: title,
          folderDetail: folderDetail,
          columnList: columnList,
          selectIndex: selectIndex,
        ),
        routeName: SmartHome3DLinkDetailPage.ROUTER);
  }
}

class _SmartHome3DLinkDetailPageState
    extends BaseState<SmartHome3DLinkDetailPage> {
  SmartHomeStoreDetailCommonViewModel _viewModel;

  List<FolderPicListBean> _folderPicList;
  FolderInfoBean _folderInfo;
  FolderPicListBean _currentPicInfo;
  PhotoPreviewInfoVo _currentVideoInfo;
  int _selectIndex = 0;

  //webview加载成功
  bool isUrlLoadComplete = false;
  StreamSubscription _detailUpdateStreamSubscription;
  @override
  void initState(){
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _viewModel = new SmartHomeStoreDetailCommonViewModel(this);
    _detailUpdateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeFolderDetailEvent>()?.listen((event) {
          _viewModel.getFolderDetailWithValueNotifier(_folderInfo?.shid??"", _folderInfo?.sfid??"", _folderInfo?.getFlg()??"", "", (folderDetailData){
            _folderPicList = folderDetailData?.folderPicList;
            _folderInfo = folderDetailData?.folderInfo;
            _currentPicInfo = _folderPicList.elementAt(_selectIndex);
            setState(() {});
          });
        });
    _selectIndex = widget?.selectIndex??0;
    _folderPicList = widget?.folderDetail?.folderPicList;
    _folderInfo = widget?.folderDetail?.folderInfo;
    _currentPicInfo = _folderPicList.elementAt(_selectIndex);


  }


  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainWidget(),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    _detailUpdateStreamSubscription?.cancel();
  }



  Widget _toMainWidget() {
    return Stack(
      children: [
        Column(
          children: [
            _toTopBarWidget(),
            Expanded(child: _toContentWidget()),
          ],
        ),
        _toBottomWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)),
      child: Container(
        height: 44,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Positioned(
              left: 16,
              child: prefix.ClickAnimateWidget(
                child: Container(
                  width: 30,
                  height: 30,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(15),
                    color: Color(0X66000000),
                  ),
                  child: Image.asset(
                    "images/top_bar_back_ico.png",
                    width: 9,
                    height: 16,
                    color: Colors.white,
                  ),
                ),
                scale: 1.4,
                onClick: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  Navigator.of(context).maybePop();
                },
              ),
            ),
            Positioned(
              right: 0,
              child: Padding(
                padding: EdgeInsets.only(right: 8),
                child: _toMoreOperationsWidget(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _toMoreOperationsWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Visibility(
          visible: false,
          child: _toOperationsWidget("icon_share", () {
            _share();
          }),
        ),
        Visibility(
          visible: !_currentPicInfo.isExample(),
          child: _toOperationsWidget("icon_more_horizontal", () {
            _more();
          }),
        ),
      ],
    );
  }

  ///下载 分享 更多
  Widget _toOperationsWidget(String resource, Function onTap) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        onTap.call();
      },
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Container(
          height: 30,
          width: 30,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
            color: Color(0X66000000),
          ),
          child: Image.asset(
            "images/${resource}.png",
            width: 20,
            height: 20,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  ///根据类型判断展示布局
  Widget _toContentWidget(){
    return _to3DLinkWidget();
  }




  InAppWebViewController _webViewController;
  ///链接
  Widget _to3DLinkWidget(){
    return Container(
      width: ScreenUtils.screenW(context),
      height: ScreenUtils.screenH(context),
      color: Colors.white,
      child: Stack(
        children: [
          Opacity(
            opacity: isUrlLoadComplete ? 1 : 0,
            child: InAppWebView(
                initialUrl: _currentPicInfo.picurl,
                onLoadStop: (controller, url){
                  print("加载完成\n" + url);
                  if(!(isUrlLoadComplete??false)){
                    setState(() {
                      isUrlLoadComplete = true;
                    });
                  }
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                onLoadError: (controller, url, code, message){
                  print("加载失败：" + message??"");
                  if(message.contains("net::ERR_INTERNET_DISCONNECTED")
                      || message.contains("404")
                      || message.contains("500")
                      || message.contains("Error")
                      || message.contains("找不到网页")
                      || message.contains("网页无法打开")){

                  }
                },
            ),
          ),
          Center(
            child: Visibility(
              visible: !isUrlLoadComplete,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    strokeWidth: 2,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    "正在加载",
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getCardBgColor_21263C(),
                        fontSize: 10),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }




  ///底部门店以及文件夹信息
  Widget _toBottomWidget() {
    //屏幕宽度
    double screenWidth = ScreenUtils.screenW(context);
    return Positioned(
      bottom: ScreenUtils.getBottomBarH(context),
      child: Visibility(
        visible: isUrlLoadComplete,
        child: Container(
          child: Container(
            width: screenWidth,
            color: Colors.transparent,
            child: Column(
              children: [
                _toFixGradientWidget(),
                _toInfoWidget(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  ///固定渐变区域
  Widget _toFixGradientWidget() {
    return IgnorePointer(
      child: Container(
        height: 80,
        width: ScreenUtils.screenW(context),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
//                Color(0xFF191E31),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.1),
              Colors.black.withOpacity(0.3),
              Colors.black.withOpacity(0.4),
//                Colors.black.withOpacity(0.7),
            ],
          ),
        ),
      ),
    );
  }

  ///信息区域
  Widget _toInfoWidget() {
    return Container(
      width: ScreenUtils.screenW(context),
      color: Colors.black.withOpacity(0.4),
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 16, top: 4, right: 16,),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ///门店信息
          Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                height: 20,
                padding: EdgeInsets.symmetric(horizontal: 8),
                margin: EdgeInsets.only(bottom: 4),
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: Colors.white.withOpacity(0.3),
                ),
                child: Text(
                  widget?.title,
                  style: TextStyle(
                      fontSize: 12,
                      color: Colors.white
                  ),
                ),
              ),
            ],
          ),

          ///标题
          Visibility(
            visible: StringUtils.isNotEmpty(_folderInfo?.title??""),
            child: Text(
              _folderInfo?.title??"",
              style: TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),

          ///描述
          Visibility(
            visible: StringUtils.isNotEmpty(_folderInfo?.backup),
            child: Container(
              child: ExpandableText(
                _folderInfo?.backup,
                expandText: "展开",
                collapseText: "收起",
                linkColor: Colors.white,
                maxLines: 3,
                style: TextStyle(
                  fontSize: 15,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          Visibility(
            visible: _folderPicList.length < 2,
            child: SizedBox(height: 16,),
          )
        ],
      ),
    );
  }


  ///分享
  _share() {
    // if(_picInfoBean == null){
    //   return;
    // }
    SSDKContentType contentType = SSDKContentTypes.image;
    if(_currentPicInfo.isVideo()){
      contentType = SSDKContentTypes.video;
    }
    if(_currentPicInfo.is3DLink()){
      contentType = SSDKContentTypes.webpage;
    }
    SharePosterMenuDialog.navigatorPushDialog(context, () {
      RouterUtils.pop(context);
      //直接分享图片
      SSDKMap params = SSDKMap()
        ..setGeneral(
            "AI前台App",
            "智能家居",
            null,
            _currentPicInfo.isImage()?_currentPicInfo?.picurl:"",
            "",
            _currentPicInfo?.picurl,
            "",
            "",
            _currentPicInfo.isVideo()?_currentPicInfo?.picurl:"",
            _currentPicInfo.isVideo()?_currentVideoInfo?.url:"",
            contentType);
      _weChatShare(context, params, "00");
    }, () {
      RouterUtils.pop(context);
      //直接分享图片
      SSDKMap params = SSDKMap()
        ..setGeneral(
            "AI前台App",
            "智能家居",
            null,
            _currentPicInfo.isImage()?_currentPicInfo?.picurl:"",
            "",
            _currentPicInfo?.picurl,
            "",
            "",
            _currentPicInfo.isVideo()?_currentPicInfo?.picurl:"",
            _currentPicInfo.isVideo()?_currentVideoInfo?.url:"",
            contentType);
      _weChatShare(context, params, "01");
    },
        bgColor: Colors.white,
        splitColor: Color(0xFFF6F7F9),
        textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        pyqResource: "images/icon_pyq_white.png");
  }

  void _weChatShare(BuildContext context, SSDKMap params, String shareFlag) {
    ShareRepository.getInstance().shareImageToWechat(context, params,
        platforms: ("00" == shareFlag)
            ? ShareSDKPlatforms.wechatTimeline
            : ShareSDKPlatforms.wechatSession);
  }

  ///更多
  _more() {
    Map<String, VoidCallback> map = {
      "编辑": () async {
        ColumnListBean currentColumn = null;
        widget?.columnList?.forEach((element) {
          if (element?.scid == _folderInfo?.scid) {
            currentColumn = element;
          }
        });
        List<SmartHomeUploadItemBean> currentList = new List();
        //链接
        currentList.add(SmartHomeUploadItemBean(
          linkUrl: _currentPicInfo?.picurl??"",
          linkCover: _folderInfo?.coverurl??"",
          netUrl: _folderInfo?.coverurl??"",
          type: "03",
          scid: _currentPicInfo?.scid??"",
          folderWidth: int.parse(_folderInfo?.coversize?.split("*")[0]),
          folderHeight: int.parse(_folderInfo?.coversize?.split("*")[1]),
          picstorage: _currentPicInfo?.picstorage??"",
          stid: _currentPicInfo?.scid??"",
          style: _currentPicInfo?.style??"99",
          backup: _currentPicInfo?.backup??"",
        ));
        SmartHomePublishPage.navigatorPush(
          context, _folderInfo?.shid, "03", widget?.columnList, currentColumn,
          currentList: currentList, sfid: _folderInfo.sfid,
          title: _folderInfo.title,
          desc: _folderInfo.backup,
          router: SmartHome3DLinkDetailPage.ROUTER,
          isCreate: false,
        );

      },
      "删除": () async {
        bool result = await CommonConfirmCancelDialog.navigatorPushDialog(
          context,
          title: "提示",
          content: "是否确认删除当前动态？",
          cancelText: "取消",
          confirmText: "确认",
          confirmBgColor:
          ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          cancelBgColor: Color(0xFFF6F7F9),
          titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
          widgetBgColor: Colors.white,
        );
        if (result ?? false) {
          _viewModel.deleteFolder(
              context,  _folderInfo?.shid, widget?.scid??"", _folderInfo?.sfid, _folderPicList
              .elementAt(0)
              .videoid);
        }
      }
    };

    CommonMoreMenuDialog.navigatorPushDialog(
      context,
      map,
      bgColor: Colors.white,
      splitColor: Color(0xFFF6F7F9),
      textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      lineColor: Color(0xFFEEEEEE),
    );
  }
}
